import { login, logout, getCommonRegion, getCommonIndustry } from '@/API/user';
import { encryption } from '@/utils/utils';
import qs from 'qs';
import {getSession,setSession} from '@/API/storage';
import Router from '@/router/index';

const state = {
  token: getSession('token') || '',  //token
  info: getSession('info') || '',  //用户信息
  region: getSession('region') || [],  //所在区域
  industry: getSession('industry') || [],  //所属行业
  config: getSession('config') || [],  //公共参数
};
const mutations = {
  SET_TOKEN: (state:any, token:string) => {
    state.token = token;
    setSession('token',token)
  },
  SET_USERINFO: (state:any, info:string) => {
    state.info = info;
    setSession('info',info)
  },
  SET_REGION: (state:any, region:any) => {
    state.region = region;
    setSession('region',region)
  },
  SET_INDUSTRY: (state:any, industry:Array<any>) => {
    state.industry = industry;
    setSession('industry',industry)
  }
};
const actions = {
  // 用户登录
  login({commit},userInfo:{account:string,password:string|number}) {
    // const user = encryption({
    //   data: userInfo,
    //   key: 'pigxpigxpigxpigx',
    //   param: ['password']
    // })
    // let data = qs.stringify({'account': userInfo.account, 'password': userInfo.password})
    return new Promise((resolve, reject) => {
      login(userInfo).then(res => {
        commit('SET_TOKEN', res.result.token);
        getCommonRegion().then(res => {
          commit('SET_REGION', res.result);
        })
        getCommonIndustry().then(res => {
          commit('SET_INDUSTRY', res.result);
        })
        commit('SET_USERINFO', {username:userInfo.account});
        resolve(res);
      }).catch((error)=>{reject(error);})
    })
  },
  //退出
  logout({commit}){
    return new Promise((resolve, reject) => {
      logout().then(res => {
        commit('SET_TOKEN', '');
        commit('SET_USERINFO', null);
        Router.replace('/login')
        resolve(res);
      }).catch((error)=>{reject(error);})
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
